package com.example.myprojectoffeixue;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by ASUS on 2016/10/27.
 */
public class AESUtil {
    public static final String bm = "UTF-8";
    public static final String IV_STRING = "1234567890123456";
    public static final String password = "1234567890qwerty";

    public static String encrypt(String cleartext) {
        String dataPassword = password;
        byte[] encryptedData = null;
        // 对密钥进行处理
        try {
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec zeroIv = new IvParameterSpec(initParam);
            byte[] enCodeFormat = new byte[0];
            enCodeFormat = dataPassword.getBytes("UTF-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            // 指定加密的算法、工作模式和填充方式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, zeroIv);
            encryptedData = cipher.doFinal(cleartext.getBytes(bm));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(encryptedData, Base64.NO_WRAP);

    }

    public static String decrypt(String encrypted) {
        String dataPassword = password;
        byte[] result = null;
        try {
            byte[] encryptedBytes = Base64.decode(encrypted, Base64.NO_WRAP);
            byte[] enCodeFormat = dataPassword.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            result = cipher.doFinal(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            return new String(result, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}